<template>

    <h1>图书管理</h1>

    <!-- 搜素栏 -->
    <div class="container">
        {{ searchBook }}
        <el-form :inline="true" :model="searchBook" class="demo-form-inline">
            <!-- 根据ISBN查询 -->
            <el-form-item label="ISBN:">
                <el-input v-model="searchBook.ISBN" placeholder="请输入ISBN号" clearable />
            </el-form-item>

            <!-- 根据分类查询 -->
            <el-form-item label="分类:">
                <el-select v-model="searchBook.category" placeholder="请选择分类" clearable>
                    <el-option label="科幻书籍" value="1" />
                    <el-option label="动漫小说" value="2" />
                    <el-option label="单词大典" value="3" />
                    <el-option label="传统经典" value="4" />
                    <el-option label="军事类" value="5" />
                    <el-option label="天文类" value="6" />
                    <el-option label="生活类" value="7" />
                    <el-option label="其他" value="0" />
                </el-select>
            </el-form-item>

            <!-- 根据时间查询 -->
            <el-form-item label="时间范围:">
                <el-date-picker v-model="searchBook.date" type="daterange" range-separator="到" start-placeholder="开始时间"
                    end-placeholder="结束时间" value-format="YYYY-MM-DD" />
                <!--         searchEmp.date:绑定数据   daterange：时间范围属性  range-separator：设置中间的分割字样 start-placeholder：开始时间的提示语 end-placeholder：结束时间的提示语                                                                                                                                              -->
            </el-form-item>

            <!-- 查询和删除 -->
            <el-form-item>
                <el-button type="primary" @click="onSubmit">查询</el-button>
                <el-button type="info" @click="remove">清除</el-button>
            </el-form-item>
        </el-form>
    </div>

    <!-- 功能部分 -->
    <div class="container">
        <el-button type="primary" @click="addbook">+ 添加图书</el-button>
        <el-button type="danger" @click="clearAll">- 批量删除</el-button>
    </div>


    <!-- 表格 -->
    <div class="container">
        <el-table :data="bookList" border style="width: 100%" @selection-change="handleSelectionChange">
            <!-- 勾选复选框 -->
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column prop="title" label="书名" width="100" />
            <el-table-column label="图片" width="120" align="center">
                <template #default="scope">
                    <img :src="scope.row.image" height="40px">
                </template>
            </el-table-column>
            <el-table-column prop="author" label="作者" width="120" />
            <el-table-column prop="ISBN" label="ISBN" width="120" />
            <el-table-column prop="category" label="图书分类" width="180">
                <template #default="scope">
                    <span v-if="scope.row.category == 1">科幻小说</span>
                    <span v-else-if="scope.row.category == 2">动漫小说</span>
                    <span v-else-if="scope.row.category == 3">单词大典</span>
                    <span v-else-if="scope.row.category == 4">传统经典</span>
                    <span v-else-if="scope.row.category == 5">军事类</span>
                    <span v-else-if="scope.row.category == 6">天文类</span>
                    <span v-else-if="scope.row.category == 7">生活类</span>
                    <span v-else="scope.row.category == 0">其他</span>
                </template>
            </el-table-column>
            <el-table-column prop="bookNum" label="数量" width="55" />
            <el-table-column prop="publish_date" label="出版时间" width="180" value-format="YYYY-MM-DD"
                format="YYYY-MM-DD" />
            <el-table-column prop="update_time" label="最后操作时间" width="180" value-format="YYYY-MM-DD"
                format="YYYY-MM-DD" />
            <el-table-column label="操作">
                <template #default="scope">
                    <el-button type="primary" size="small" @click="edit(scope.row.id)">
                        编辑
                    </el-button>
                    <el-button size="small" type="danger" @click="deleteById(scope.row.id)">
                        删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
    </div>

    <!-- 分页条 -->
    <div class="container">
        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[5, 10, 20, 30, 40]"
            :size="size" :disabled="disabled" :background="background" layout="total, sizes, prev, pager, next, jumper"
            :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </div>


    <!-- 添加/编辑图书 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500" center>
        {{ tableData }}
        <el-form :model="tableData" label-width="auto" style="max-width: 600px" :rules="rules" ref="BooksFromRef">
            <el-form-item label="添加书名:" prop="title">
                <el-input v-model="tableData.title" placeholder="请输入书名" />
            </el-form-item>
            <el-form-item label="添加书名作者:" prop="author">
                <el-input v-model="tableData.author" placeholder="请输入书名作者" />
            </el-form-item>
            <el-form-item label="添加ISBN:" prop="ISBN">
                <el-input v-model="tableData.ISBN" placeholder="请输入ISBN" />
            </el-form-item>
            <el-form-item label="图书图片">
                <el-upload class="avatar-uploader" action="/Books/upload" :show-file-list="false"
                    :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                    <img v-if="tableData.image" :src="tableData.image" class="avatar" />
                    <el-icon v-else class="avatar-uploader-icon">
                        <Plus />
                    </el-icon>
                </el-upload>
            </el-form-item>
            <el-form-item label="图书数量" prop="bookNum">
                <el-input v-model="tableData.bookNum" placeholder="请输入图书数量" />
            </el-form-item>
            <el-form-item label="添加图书分类:" prop="categorys">
                <el-select v-model="tableData.category" placeholder="请输入图书分类">
                    <el-option v-for="b in books" :key="b.value" :label="b.name" :value="b.value" />
                </el-select>
            </el-form-item>
            <el-form-item label="图书出版时间:">
                <el-col :span="11">
                    <el-date-picker v-model="tableData.publish_date" type="date" placeholder="请选择时间" style="width: 100%"
                        value-format="YYYY-MM-DD" format="YYYY-MM-DD" />
                </el-col>
            </el-form-item>
        </el-form>

        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="save">
                    提交
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script lang="ts" setup>
import { ref, watch, onMounted } from 'vue'
import type { ComponentSize } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import { addApiBook, queryApiBook, deleteApiBook, getByidApi, updateBookApi } from '@/api/books'



// 图书分类数据
const books = ref([{ name: '科幻书籍', value: 1 }, { name: '动漫小说', value: 2 }, { name: '单词大典', value: 3 },
    {name:'传统经典',value:4},{name:'军事类',value:5},{name:'天文类',value:6},{name:'生活类',value:7} ,{ name: '其他', value: 0 }
])

//搜索栏数据对象
const searchBook = ref({ ISBN: '', category: '', date: [], begin: '', end: '' })

const tableData = ref({
    id: '',
    title: '',
    image: '',
    author: '',
    category: '',
    publish_date: '',
    updata_time: '',
    ISBN: '',
    bookNum:''
})

// 初始化查询
onMounted(() => {
    onSubmit()
})

// 表格渲染数据
const bookList = ref([])

// 提交
const onSubmit = async () => {
    const reuslt = await queryApiBook(searchBook.value.ISBN, searchBook.value.category, searchBook.value.begin, searchBook.value.end, currentPage.value, pageSize.value)
    if (reuslt && typeof reuslt === 'object') {
        const data = reuslt.data || reuslt
        bookList.value = data.records || []
        total.value = data.total || 0
    } else {
        ElMessage.error("查询失败")
    }
}

// 删除图书
const remove = () => {
    searchBook.value = { ISBN: '', category: '', date: [], begin: '', end: '' }
    onSubmit()
}

// 新增图书
const addbook = () => {
    dialogVisible.value = true
    dialogTitle.value = '添加图书'
    tableData.value = {
        id: '',
        title: '',
        image: '',
        author: '',
        category: '',
        publish_date: '',
        updata_time: '',
        ISBN: '',
        bookNum:''
    }

    //重置表单的校验规则 --提示信息
    if (BooksFromRef.value) {
        BooksFromRef.value.resetFields();
    }
}



//给时间添加watch侦听
watch(() => searchBook.value.date, (newVal, oldVal) => {
    if (newVal && newVal.length == 2) {
        searchBook.value.begin = newVal[0]
        searchBook.value.end = newVal[1]
    } else {
        searchBook.value.begin = ''
        searchBook.value.end = ''
    }
})

// 编辑
const edit = async (id) => {
    dialogVisible.value = true
    dialogTitle.value = '编辑图书'
    const result = await getByidApi(id)
    if (result) {
        tableData.value = result.data
    }

}

//批量删除用户信息
//记录勾选的员工的id
const selectedIds = ref([]);
const handleSelectionChange = (selection) => {
    selectedIds.value = selection.map(item => item.id);
}

//批量删除
const clearAll = () => {
    //弹出确认框
    ElMessageBox.confirm('您确认删除该员工吗?', '提示',
        { confirmButtonText: '确认', cancelButtonText: '取消', type: 'warning' }
    ).then(async () => { //确认
        if (selectedIds.value && selectedIds.value.length > 0) {
            const result = await deleteApiBook(selectedIds.value);
            if (result) {
                ElMessage.success('删除成功');
                onSubmit();
            } else {
                ElMessage.error('删除失败');
            }
        } else {
            ElMessage.info('您没有选择任何要删除的数据');
        }
    }).catch(() => { //取消
        ElMessage.info('您已取消删除');
    })

}


// 根据id删除图书
const deleteById = async (id) => {
    //弹出确认框
    ElMessageBox.confirm('您确认删除该员工吗?', '提示',
        { confirmButtonText: '确认', cancelButtonText: '取消', type: 'warning' }
    ).then(async () => { //确认
        const result = await deleteApiBook(id);
        if (result) {
            ElMessage.success('删除成功');
            onSubmit();
        } else {
            ElMessage.error('删除失败');
        }
    }).catch(() => { //取消
        ElMessage.info('您已取消删除');
    })
}

// 保存功能
const save = async () => {
    //判断校验是否通过
    if (!BooksFromRef.value) return
    //检验原则
    BooksFromRef.value.validate(async (valid) => {
        if (valid) {
            let result;
            if (tableData.value.id) {
                result = await updateBookApi(tableData.value)
                if (result) {
                    ElMessage.success("修改成功")
                    onSubmit()
                    dialogVisible.value = false;
                } else {
                    ElMessage.error("修改失败")
                    onSubmit()
                }
            } else {
                result = await addApiBook(tableData.value)
                if (result) {
                    ElMessage.success("添加成功")
                    onSubmit()
                    dialogVisible.value = false;
                } else {
                    ElMessage.error("添加失败")
                    onSubmit()
                }
            }
        } else {
            ElMessage.error("图书数据出错")
        }
    })
}

// 添加图书
const dialogVisible = ref(false)

// 弹窗标题
const dialogTitle = ref('添加图书')

// 初始页码
const currentPage = ref(1)
// 每页记录数
const pageSize = ref(10)
const size = ref<ComponentSize>('default')
const background = ref(true)
const disabled = ref(false)
const total = ref(0) // 页码总记录数

const handleSizeChange = (val: number) => {
    pageSize.value = val;
    onSubmit()
}
const handleCurrentChange = (val: number) => {
    currentPage.value = val;
    onSubmit()
}

//文件上传
const imageUrl = ref('')
// 图片上传成功后触发
const handleAvatarSuccess = (response) => {
    tableData.value.image = response.data;
}
// 文件上传之前触发
const beforeAvatarUpload = (rawFile) => {
    if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
        ElMessage.error('只支持上传图片')
        return false
    } else if (rawFile.size / 1024 / 1024 > 10) {
        ElMessage.error('只能上传10M以内图片')
        return false
    }
    return true
}


//表单校验规则
const rules = ref({
    title: [
        { required: true, message: '请输入图书名称', trigger: 'blur' },
        { min: 2, max: 20, message: '图书名称长度应在2到20个字符之间', trigger: 'blur' }
    ],
    author: [
        { required: true, message: '请输入作者名字', trigger: 'blur' },
        { min: 2, max: 10, message: '作者名字长度应在2到10个字符之间', trigger: 'blur' }
    ],
    ISBN: [
        { required: true, message: '请输入ISBN号', trigger: 'blur' },
        { min: 12, max: 12, message: 'ISBN号长度为12', trigger: 'blur' }
    ],
    authors: [
        { required: true, message: '请选择图书分类', trigger: 'change' }
    ],
    phone: [
        { required: true, message: '请输入手机号', trigger: 'blur' },
        { pattern: /^1\d{10}$/, message: '请输入有效的手机号', trigger: 'blur' }
    ],
    bookNum:[
        { required: true, message: '请输入图书数量', trigger: 'blur' },
    ]
});

const BooksFromRef = ref()

</script>

<style>
.container {
    margin: 15px 0px;
}

.demo-form-inline .el-input {
    --el-input-width: 220px;
}

.demo-form-inline .el-select {
    --el-select-width: 220px;
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 78px;
    height: 78px;
    text-align: center;
    /* 添加灰色的虚线边框 */
    border: 1px dashed var(--el-border-color);
}
</style>
